package com.j256.ormlite.db;

import com.j256.ormlite.field.DataPersister;
import com.j256.ormlite.field.FieldType;
import com.j256.ormlite.field.types.*;
import com.j256.ormlite.hmos.DatabaseTableConfigUtil;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.DatabaseTableConfig;
import com.j256.ormlite.utils.Constants;

import java.sql.SQLException;

/**
 * SqlLiteHmosDatabaseType
 *
 */
public class SqlLiteHarmonyDatabaseType extends BaseSqliteDatabaseType {
    @Override
    public boolean isDatabaseUrlThisType(String url, String dbTypePart) {
        return true;
    }

    @Override
    public String getDatabaseName() {
        return Constants.DATABASENAME;
    }

    @Override
    protected void appendDateType(StringBuilder sb, FieldType fieldType, int fieldWidth) {
        appendStringType(sb, fieldType, fieldWidth);
    }

    @Override
    public void appendEscapedEntityName(StringBuilder sb, String name) {
        /*
         * Sqlite doesn't seem to be able to handle the 'foo'.'bar' form of the column name which is for
         * database.table I think so we just default to be single quoted like before.
         */

        sb.append('`').append(name).append('`');
    }

    @Override
    protected void appendBooleanType(StringBuilder sb, FieldType fieldType, int fieldWidth) {
        // we have to convert booleans to numbers
        appendShortType(sb, fieldType, fieldWidth);
    }

    @Override
    public DataPersister getDataPersister(DataPersister defaultPersister, FieldType fieldType) {
        if (defaultPersister == null) {
            return super.getDataPersister(defaultPersister, fieldType);
        }

        switch (defaultPersister.getSqlType()) {
            case DATE:
                /*
                 * We need to map the dates into their string equivalents because of mapping issues with Sqlite's
                 * default date string formats.
                 */
                if (defaultPersister instanceof TimeStampType) {
                    return TimeStampStringType.getSingleton();
                } else if (defaultPersister instanceof SqlDateType) {
                    return SqlDateStringType.getSingleton();
                } else {
                    return DateStringType.getSingleton();
                }
            default:
                return super.getDataPersister(defaultPersister, fieldType);
        }
    }

    @Override
    public boolean isNestedSavePointsSupported() {
        return false;
    }

    @Override
    public boolean isBatchUseTransaction() {
        return true;
    }

    @Override
    public <T> DatabaseTableConfig<T>
    extractDatabaseTableConfig(ConnectionSource connectionSource, Class<T> clazz) throws SQLException {
        return DatabaseTableConfigUtil.fromClass(connectionSource, clazz);
    }
}
